<template>
  <div class="withdraw-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2 class="page-title">
            <i class="el-icon-money"></i>
            提现管理
          </h2>
          <p class="page-description">管理您的提现申请，每月十五号后可提现上月及以前的收益</p>
        </div>
        <div class="header-right">
          <el-button
            icon="el-icon-refresh"
            @click="refreshAllData">
            刷新数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 收益概览 -->
    <div class="income-overview">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="income-card total-income-card">
            <div class="card-content">
              <div class="card-icon total-icon">
                <i class="el-icon-coin"></i>
              </div>
              <div class="card-info">
                <div class="card-title">总收益</div>
                <div class="card-value">{{ formatPrice(incomeStats.totalIncome || 0) }}</div>
                <div class="card-unit">元</div>
              </div>
              <div class="income-types">
                <div class="income-type-item adincome-item" @click="goToCommissionDetail(1)">
                  <div class="income-type-info">
                    <div class="income-type-title">广告收益</div>
                    <div class="income-type-value">{{ formatPrice(incomeStats.adincome || 0) }}</div>
                  </div>
                </div>
                <div class="income-type-item alliance-item" @click="goToCommissionDetail(2)">
                  <div class="income-type-info">
                    <div class="income-type-title">异业联盟收益</div>
                    <div class="income-type-value">{{ formatPrice(incomeStats.alliancelncome || 0) }}</div>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="income-card">
            <div class="card-content">
              <div class="card-icon available-icon">
                <i class="el-icon-wallet"></i>
              </div>
              <div class="card-info">
                <div class="card-title">可提现金额</div>
                <div class="card-value">{{ formatPrice(incomeStats.availableAmount || 0) }}</div>
                <div class="card-unit">元</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="income-card">
            <div class="card-content">
              <div class="card-icon pending-icon">
                <i class="el-icon-time"></i>
              </div>
              <div class="card-info">
                <div class="card-title">待审核提现</div>
                <div class="card-value">{{ formatPrice(incomeStats.pendingAmount || 0) }}</div>
                <div class="card-unit">元</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 提现申请 -->
    <div class="withdraw-apply">
      <el-card>
        <div slot="header" class="card-header">
          <span>提现申请</span>
          <el-button
            type="primary"
            icon="el-icon-plus"
            :disabled="!canWithdraw"
            @click="showWithdrawDialog">
            申请提现
          </el-button>
        </div>

        <div class="withdraw-rules">
          <el-alert
            title="提现规则"
            type="info"
            :closable="false"
            show-icon>
            <ul>
              <li>每月十五号后可提现上月及以前的收益</li>
              <li>提现金额将通过支付宝转入您的账户</li>
              <li>单次提现金额不能超过可提现金额</li>
              <li>提现申请提交后需要审核，请耐心等待</li>
            </ul>
          </el-alert>
        </div>
      </el-card>
    </div>

    <!-- 提现记录 -->
    <div class="withdraw-records">
      <el-card>
        <div slot="header" class="card-header">
          <span>提现记录</span>
        </div>

        <!-- 搜索筛选 -->
        <div class="search-section">
          <el-form :model="searchForm" :inline="true" class="search-form">
            <el-form-item label="申请时间">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                style="width: 240px">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="审核状态">
              <el-select v-model="searchForm.statue" placeholder="请选择状态" clearable style="width: 120px">
                <el-option label="待审核" :value="1"></el-option>
                <el-option label="已通过" :value="2"></el-option>
                <el-option label="已拒绝" :value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
              <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 提现记录表格 -->
        <configurable-table
          :columns="tableColumns"
          :data="withdrawList"
          :loading="loading"
          :show-pagination="true"
          :current-page.sync="pagination.current"
          :page-size.sync="pagination.size"
          :pagination-total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          pagination-layout="total, sizes, prev, pager, next, jumper"
          @page-change="loadWithdrawData"
          stripe
          style="width: 100%">
          <!-- 提现金额列 -->
          <template slot="amount" slot-scope="{ row }">
            <span class="amount-text">{{ formatPrice(row.amount) }}</span>
          </template>
          <!-- 审核状态列 -->
          <template slot="statue" slot-scope="{ row }">
            <el-tag :type="getStatusType(row.statue)">
              {{ getStatusText(row.statue) }}
            </el-tag>
          </template>
          <!-- 申请时间列 -->
          <template slot="createTime" slot-scope="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
          <!-- 审核时间列 -->
          <template slot="updateTime" slot-scope="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
          <!-- 操作列 -->
          <template slot="actions" slot-scope="{ row }">
            <el-button
              type="text"
              size="small"
              @click="handleViewDetail(row)">
              查看详情
            </el-button>
          </template>
        </configurable-table>
      </el-card>
    </div>

    <!-- 提现申请对话框 -->
    <el-dialog
      title="申请提现"
      :visible.sync="withdrawDialogVisible"
      width="500px"
      :close-on-click-modal="false">
      <el-form
        :model="withdrawForm"
        :rules="withdrawRules"
        ref="withdrawForm"
        label-width="100px">
        <el-form-item label="可提现金额">
          <span class="available-amount">{{ formatPrice(incomeStats.availableAmount || 0) }} 元</span>
        </el-form-item>
        <el-form-item label="提现金额" prop="amount">
          <el-input-number
            v-model="withdrawForm.amount"
            :min="0.01"
            :max="(incomeStats.availableAmount || 0) / 100"
            :precision="2"
            :step="0.01"
            style="width: 200px">
          </el-input-number>
          <span class="unit-text">元</span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="withdrawForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入提现备注（可选）"
            maxlength="200"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="withdrawDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="handleSubmitWithdraw">
          确认提现
        </el-button>
      </div>
    </el-dialog>

    <!-- 提现详情对话框 -->
    <el-dialog
      title="提现详情"
      :visible.sync="detailDialogVisible"
      width="600px">
      <el-descriptions :column="2" border v-if="selectedWithdraw">
        <el-descriptions-item label="提现ID">{{ selectedWithdraw.id }}</el-descriptions-item>
        <el-descriptions-item label="提现金额">
          <span class="amount-text">{{ formatPrice(selectedWithdraw.amount) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getStatusType(selectedWithdraw.statue)">
            {{ getStatusText(selectedWithdraw.statue) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ formatDateTime(selectedWithdraw.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ formatDateTime(selectedWithdraw.updateTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ selectedWithdraw.remark || '-' }}</el-descriptions-item>
        <el-descriptions-item label="拒绝原因" :span="2" v-if="selectedWithdraw.reason">
          <span class="reason-text">{{ selectedWithdraw.reason }}</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { getMerchantWithdrawPage, applyMerchantWithdraw, getMerchantWithdrawDetail, getIncomeStats } from '@/api/merchant/withdraw'

export default {
  name: 'MerchantWithdraw',
  data() {
    return {
      loading: false,
      submitLoading: false,

      // 收益统计
      incomeStats: {
        totalIncome: 0,      // 总收益
        availableAmount: 0,  // 可提现金额
        pendingAmount: 0,    // 待审核提现金额
        adincome: 0,         // 广告收益
        alliancelncome: 0    // 异业联盟收益
      },

      // 搜索表单
      searchForm: {
        dateRange: [],
        statue: null
      },

      // 提现记录列表
      withdrawList: [],

      // 表格列配置
      tableColumns: [
        { prop: 'id', label: '提现ID', minWidth: 100, align: 'center' },
        { prop: 'amount', label: '提现金额', minWidth: 120, align: 'right', slot: 'amount' },
        { prop: 'statue', label: '审核状态', minWidth: 100, align: 'center', slot: 'statue' },
        { prop: 'createTime', label: '申请时间', minWidth: 150, align: 'center', slot: 'createTime' },
        { prop: 'updateTime', label: '审核时间', minWidth: 150, align: 'center', slot: 'updateTime' },
        { prop: 'reason', label: '拒绝原因', minWidth: 150, showOverflowTooltip: true },
        { label: '操作', minWidth: 100, align: 'center', slot: 'actions', fixed: 'right' }
      ],

      // 分页
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },

      // 提现申请对话框
      withdrawDialogVisible: false,
      withdrawForm: {
        amount: 0,
        remark: ''
      },
      withdrawRules: {
        amount: [
          { required: true, message: '请输入提现金额', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '提现金额必须大于0', trigger: 'blur' }
        ]
      },

      // 详情对话框
      detailDialogVisible: false,
      selectedWithdraw: null
    }
  },
  computed: {
    // 是否可以提现
    canWithdraw() {
      const today = new Date()
      const day = today.getDate()
      const availableAmount = this.incomeStats.availableAmount || 0

      // 每月十五号后可提现，且有可提现金额
      return day >= 15 && availableAmount > 0
    }
  },
  mounted() {
    this.refreshAllData()
  },
  methods: {
    // 刷新所有数据
    async refreshAllData() {
      this.loading = true
      try {
        // 重置分页到第一页和搜索条件
        this.pagination.current = 1
        // 同时加载所有数据，确保数据一致性
        await Promise.all([
          this.loadIncomeStats(),
          this.loadWithdrawData()
        ])
        this.$message.success('数据刷新成功')
      } catch (error) {
        Logger.error('刷新数据失败:', error)
        this.$message.error('刷新数据失败')
      } finally {
        this.loading = false
      }
    },
    // 加载收益统计
    async loadIncomeStats() {
      try {
        Logger.log('=== 加载通用收益统计 ===')

        // 只调用通用收益统计接口
        const generalStatsResponse = await getIncomeStats().catch(error => {
          Logger.error('通用收益统计接口调用失败:', error)
          return { code: 500, data: {} }
        })

        Logger.log('通用收益统计响应:', generalStatsResponse)

        // 处理通用收益统计（广告收益、异业联盟收益）
        if (generalStatsResponse.code === 0) {
          const data = generalStatsResponse.data

          this.incomeStats = {
            totalIncome: data.totalIncome || 0,   // 总收益
            availableAmount: data.availableAmount || 0,   // 可提现金额
            pendingAmount: data.pendingAmount || 0, // 待审核提现金额
            adincome: data.adincome || 0, // 广告收益
            alliancelncome: data.alliancelncome || 0  // 异业联盟收益
          }
        } else {
          Logger.warn('通用收益统计接口返回错误:', generalStatsResponse.data)
          this.incomeStats = {
            totalIncome: 0,
            availableAmount: 0,
            pendingAmount: 0,
            adincome: 0,
            alliancelncome: 0
          }
        }

        Logger.log('收益统计加载成功:', this.incomeStats)
      } catch (error) {
        Logger.error('加载收益统计失败:', error)
        this.$message.error('加载收益统计失败: ' + error.message)
        // 设置默认值
        this.incomeStats = {
          totalIncome: 0,
          availableAmount: 0,
          pendingAmount: 0,
          adincome: 0,
          alliancelncome: 0
        }
      }
    },

    // 加载提现记录
    async loadWithdrawData() {
      this.loading = true
      try {
        Logger.log('=== 加载商家提现记录 ===')

        const params = {
          pageIndex: this.pagination.current,
          pageSize: this.pagination.size,
          userId: this.$store.state.user.id // 商家ID
        }

        // 添加时间筛选
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startTime = this.searchForm.dateRange[0] + ' 00:00:00'
          params.endTime = this.searchForm.dateRange[1] + ' 23:59:59'
        }

        // 添加状态筛选
        if (this.searchForm.statue !== null && this.searchForm.statue !== '') {
          params.statue = this.searchForm.statue
        }

        Logger.log('提现记录查询参数:', params)

        const response = await getMerchantWithdrawPage(params)
        Logger.log('提现记录响应:', response.data)

        if (response.code === 0 && response.data) {
          this.withdrawList = response.data.list || []
          this.pagination.total = response.data.total || 0
          Logger.log('提现记录数据:', this.withdrawList)
        } else {
          Logger.log('未获取到提现记录数据')
          this.withdrawList = []
          this.pagination.total = 0
        }
      } catch (error) {
        Logger.error('加载提现记录失败:', error)
        this.$message.error('加载提现记录失败，请重试')
        this.withdrawList = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },

    // 显示提现申请对话框
    showWithdrawDialog() {
      if (!this.canWithdraw) {
        this.$message.warning('每月十五号后才可申请提现，或当前没有可提现金额')
        return
      }

      this.withdrawForm = {
        amount: 0,
        remark: ''
      }
      this.withdrawDialogVisible = true
    },

    // 处理提现错误提示
    handleWithdrawError(error) {
      // 优先显示 detail 字段的详细信息
      if (error.detail) {
        this.$message.error(error.detail)
        return
      }
      // 其次显示 message 字段
      if (error.message) {
        this.$message.error(error.message)
        return
      }
      // 兼容旧格式的 msg 字段
      if (error.msg) {
        this.$message.error(error.msg)
        return
      }
      // 默认错误提示
      this.$message.error('提现申请失败，请重试')
    },

    // 提交提现申请
    async handleSubmitWithdraw() {
      try {
        await this.$refs.withdrawForm.validate()

        this.submitLoading = true

        const submitData = {
          amount: Math.round(this.withdrawForm.amount * 100), // 转换为分
          userId: this.$store.state.user.id,
          userType: this.$store.state.user.userType  // 添加用户类型参数
        }

        Logger.log('=== 提交提现申请 ===')
        Logger.log('提现申请数据:', submitData)

        const response = await applyMerchantWithdraw(submitData)
        Logger.log('提现申请响应:', response)

        if (response.code === 0) {
          this.$message.success('提现申请提交成功，请等待审核')
          this.withdrawDialogVisible = false
          this.loadWithdrawData() // 刷新提现记录
          this.loadIncomeStats()  // 刷新收益统计
        } else {
          // 使用统一的错误处理函数
          this.handleWithdrawError(response.data || response)
        }
      } catch (error) {
        Logger.error('提现申请失败:', error)
        // 处理异常情况下的错误信息
        if (error.response && error.response.data) {
          this.handleWithdrawError(error.response.data)
        } else if (error.data) {
          this.handleWithdrawError(error.data)
        } else {
          this.$message.error('提现申请失败，请重试')
        }
      } finally {
        this.submitLoading = false
      }
    },

    // 查看提现详情
    async handleViewDetail(row) {
      try {
        Logger.log('=== 查看提现详情 ===')
        Logger.log('提现ID:', row.id)

        const response = await getMerchantWithdrawDetail(row.id)
        Logger.log('提现详情响应:', response.data)

        if (response.code === 0 && response.data) {
          this.selectedWithdraw = response.data
          this.detailDialogVisible = true
        } else {
          this.$message.error('获取提现详情失败')
        }
      } catch (error) {
        Logger.error('获取提现详情失败:', error)
        this.$message.error('获取提现详情失败，请重试')
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadWithdrawData()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        dateRange: [],
        statue: null
      }
      this.pagination.current = 1
      this.loadWithdrawData()
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        1: 'warning', // 待审核
        2: 'success', // 已通过
        3: 'danger'   // 已拒绝
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '待审核',
        2: '已通过',
        3: '已拒绝'
      }
      return statusMap[status] || '未知'
    },

    // 格式化价格
    formatPrice(price) {
      if (!price) return '0.00'
      return (price / 100).toFixed(2)
    },

    // 跳转到收益详情页
    goToCommissionDetail(platform) {
      // platform: 1=广告收益, 2=异业联盟收益
      this.$router.push({
        name: 'MerchantIncomeDetail',
        query: { incomeType: platform }
      })
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.withdraw-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left {
  flex: 1;
}

.header-right {
  display: flex;
  align-items: center;
}

.page-title {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.income-overview {
  margin-bottom: 20px;
}

.income-card {
  height: 120px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.income-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.total-income-card .card-content {
  justify-content: space-between;
}

.income-types {
  display: flex;
  flex-direction: row;
  gap: 24px;
  margin-left: 20px;
  padding-left: 20px;
  border-left: 1px solid rgba(0, 0, 0, 0.1);
}

.income-type-item {
  position: relative;
  padding: 12px 16px;
  padding-left: 48px;
  border-radius: 6px;
  background-color: rgba(255, 255, 255, 0.6);
  transition: all 0.3s;
  cursor: pointer;
}

.income-type-item:hover {
  background-color: rgba(255, 255, 255, 0.8);
  transform: translateY(-1px);
}

.income-type-item::before {
  content: '';
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 32px;
  border-radius: 2px;
}

.adincome-item::before {
  background: linear-gradient(135deg, #409eff, #66b1ff);
}

.alliance-item::before {
  background: linear-gradient(135deg, #9c27b0, #ba68c8);
}

.income-type-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.income-type-title {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

.income-type-value {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.total-icon {
  background: linear-gradient(135deg, #409eff, #67c23a);
}

.available-icon {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.pending-icon {
  background: linear-gradient(135deg, #e6a23c, #f0c78a);
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-unit {
  font-size: 12px;
  color: #909399;
}

.withdraw-apply {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.withdraw-rules {
  margin-top: 16px;
}

.withdraw-rules ul {
  margin: 8px 0 0 0;
  padding-left: 20px;
}

.withdraw-rules li {
  margin-bottom: 4px;
  color: #606266;
}

.withdraw-records {
  margin-bottom: 20px;
}

.search-section {
  margin-bottom: 16px;
}

.search-form {
  margin-bottom: 0;
}

.amount-text {
  color: #67c23a;
  font-weight: 600;
}

.available-amount {
  color: #67c23a;
  font-weight: 600;
  font-size: 16px;
}

.unit-text {
  margin-left: 8px;
  color: #909399;
}

.reason-text {
  color: #f56c6c;
}


/* 响应式设计 */
@media (max-width: 768px) {
  .income-overview .el-col {
    margin-bottom: 16px;
  }

  .search-form {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .search-form .el-form-item {
    margin-right: 0;
  }
}
</style>
